package com.authentications.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.authentications.utils.JwtSpringSecurityTokenUtils;
import com.authentications.utils.ResultBean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName JwtAuthenticationFilter
 * @Author xiezhuocai
 * @Description 解析token类
 * @Date 2021/12/20 8:42
 */
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    JwtSpringSecurityTokenUtils tokenUtils;

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager, JwtSpringSecurityTokenUtils tokenUtils) {
        super(authenticationManager);
        this.tokenUtils = tokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        String tokenHeader = request.getHeader(JwtSpringSecurityTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtSpringSecurityTokenUtils.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        } catch (RuntimeException e) {
            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            //String reason = "统一处理，原因：" + e.getMessage();
            response.getWriter().write(JSONObject.toJSONString(ResultBean.error("System error",500,e.getMessage())));
            response.getWriter().close();
            response.flushBuffer();
            return;
        }
        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws RuntimeException {
        String token = tokenHeader.replace(JwtSpringSecurityTokenUtils.TOKEN_PREFIX, "");
        boolean expiration = tokenUtils.isExpiration(token);
        if (expiration) {
            throw new RuntimeException("token超时了");
        } else {
            String username = tokenUtils.getUsername(token);
            List role = tokenUtils.getUserRole(token);
            if (username != null) {
                return new UsernamePasswordAuthenticationToken(username, null,
                        getAuthorities(role)
                );
            }
        }
        return null;
    }

    public Collection getAuthorities(List<String> authorities) {
        List list = new ArrayList();
        for (String authority : authorities) {
            list.add(new SimpleGrantedAuthority(authority));
        }
        return list;
    }

}

